<html>
<script>
	var enabled = false;
	var req;
	var tabFeeds = [];
	var comPorts = [];

	chrome.self.onConnect.addListener(function(port) {
  		comPorts[port.tab.id] = port;
	    port.onMessage.addListener(function(feedUrls) {
			try {
				tabFeeds[port.tab.id] = [];
				for (var feed in feedUrls) {
					tabFeeds[port.tab.id].push({
						href: feedUrls[feed].href,
						title: feedUrls[feed].title
					});
				}
				if (tabFeeds[port.tab.id].length == 0) {
//					icon.src = "icon_disabled.png";
					enabled = false;
				}
				else {
//					icon.src = "icon.png";
					enabled = true;
					
//					chrome.tabs.getSelected(null, function(tab){
						chrome.pageActions.enableForTab("subscribr", {
							tabId: port.tab.id,
							url: port.tab.url
						});
//					})
					/**
			 		* Changing the icon in a page action doesn`t seem to work yet
			 		* so we skip the test
			 		*/
//					req = new XMLHttpRequest();
//					req.onload = handleResponse;
//					req.open("GET",
//						"http://www.google.com/reader/api/0/subscribed?s=feed%2F" + feedUrl,
//						false);
//					req.send(null);	
				}
			} catch(e)	{
				comPorts[port.tab.id].postMessage("Error:\n"+e.message);
			}
		});
	});

	chrome.pageActions.onExecute.addListener(function(pa)	{
		if (enabled) {
			chrome.tabs.getSelected(null,function(tab)	{
				try {
//					for(var test in chrome.pageActions)	{
//						comPorts[tab.id].postMessage("Debug\n"+test+": "+chrome.pageActions[test]);
//					}
					var urls = [];
					for (var feed in tabFeeds[tab.id]) {
						req = new XMLHttpRequest();
//						req.onload = handleResponse;
						req.open("GET",
							"http://www.google.com/reader/api/0/subscribed?s=feed%2F" + tabFeeds[tab.id][feed].href,
							false);
						req.send(null);
						
						if(req.responseText=="true")	{
							var icon="icon_subscribed.png";
						}	else	{
							var icon="icon.png";
						}
						
						urls.push({
							href: "http://www.google.com/reader/view/feed/" +
							encodeURIComponent(tabFeeds[tab.id][feed].href),
							title: tabFeeds[tab.id][feed].title,
							icon: icon
						});
					}
					if(urls.length==1)	{
						chrome.tabs.create({
							url: urls[0].href,
							selected: true
						});
						enabled = false;
					}	else	{
						comPorts[tab.id].postMessage(urls);
					}
				} catch(e)	{
					comPorts[tab.id].postMessage("Error:\n"+e.message);
				}
			})
		}
	})
</script>
</html>
